package com.atkxp.controller;

import com.atkxp.pojo.Blog;
import com.atkxp.pojo.MyPair;
import com.atkxp.pojo.Page;
import com.atkxp.pojo.User;
import com.atkxp.service.BlogService;
import com.atkxp.service.CommentService;
import com.atkxp.service.UserService;
import org.ocpsoft.prettytime.PrettyTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * @author user
 * @declaration
 * @create 2023/1/17-15:24
 */
@Controller
@RequestMapping("/tag")
public class TagController {

    @Autowired
    public BlogService blogService;

    @Autowired
    private UserService userService;

    @Autowired
    private CommentService commentService;

    @RequestMapping("/toClassification")
    public String toClassification(){
        return "classification";
    }

    @RequestMapping("/classification")
    public String classification(String Tag, HttpServletRequest req){
        System.out.println(Tag);
        String basePath = req.getScheme() + "://" +
                req.getServerName() +
                ":" + req.getServerPort() +
                req.getContextPath() + "/";
        int pageNum;
        int pageSize;
        if(req.getParameter("pageNum") == null || Integer.parseInt(req.getParameter("pageNum")) <= 0){
            pageNum = 1;
        }else{
            pageNum = Integer.parseInt(req.getParameter("pageNum"));
        }
        if(req.getParameter("pageSize") == null){
            pageSize = Page.PAGE_SIZE;
        }else{
            pageSize = Integer.parseInt(req.getParameter("pageSize"));
        }
        Map map = new HashMap();
        map.put("Tag", Tag);
        map.put("pageNum", pageNum);
        map.put("pageSize", pageSize);
        Page<Blog> page = blogService.getBlogByTag(map);
        page.setUrl(basePath + "/tag/classification?Tag=" + Tag);
        List<Blog> blogs = page.getItem();
        Map<Blog, MyPair<String, MyPair<User, Integer>>> map2 = new LinkedHashMap();
        for(Blog blog : blogs){
            map2.put(blog, new MyPair<String, MyPair<User, Integer>>(new PrettyTime().format(blog.getBlogDate()), new MyPair<User, Integer>(userService.showUserInfoByName(blog.getUserName()), commentService.getCommentNum(blog.getId()))));
        }
        req.setAttribute("page", page);
        req.setAttribute("blogs", map2);
        return "ClassificationBlog";
    }
}
